package cn.keniykey.mc.landterritory.command.landadmin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import org.bukkit.command.CommandSender;

import cn.keniykey.mc.landterritory.command.AbCommandBase;
import cn.keniykey.mc.landterritory.config.LanguageManager;
import cn.keniykey.mc.landterritory.land.LandManager;
import cn.keniykey.mc.landterritory.land.api.ELandType;
import cn.keniykey.mc.landterritory.land.api.Land;
import cn.keniykey.mc.landterritory.landflag.LandFlag;
import cn.keniykey.mc.landterritory.landflag.LandFlagManager;

public final class CommandLand extends AbCommandBase {
	private static final List<String> tablist = new ArrayList<>(Arrays.asList("clearflag"));
	
	CommandLand() {
		super("land", "land.command.land", false);
	}
	
	@Override
	public boolean execute(CommandSender sender, List<String> parameter) {
		final int size = parameter.size();
		if(size == 1) {
			switch(parameter.get(0).toLowerCase()) {
			case "clearflag":
				sender.sendMessage(LanguageManager.getChatLang(1203121));
				clearUnUsedLandFlagInLand();
				sender.sendMessage(LanguageManager.getChatLang(1203122));
				return true;
			default:
			}
		}
		return false;
	}
	@Override
	public List<String> prompt(CommandSender sender, List<String> parameter) {
		if(parameter.size() == 1) return tablist;
		return emptylist;
	}
	@Override
	public String usage() {
		return LanguageManager.getLang(1203120);
	}
	
	private static void clearUnUsedLandFlagInLand() {
		for(final ELandType type : ELandType.values()) {
			for(final Land land : LandManager.getLandManager().getServerLands(type)) {
				if(land.isDeleted()) continue;
				boolean update = false;
				final Iterator<Entry<String, Set<String>>> it = land.getFlags().entrySet().iterator();
				while(it.hasNext()) {
					final Entry<String, Set<String>> entry = it.next();
					final String flagname = entry.getKey();
					final LandFlag flag = LandFlagManager.getFlagManager().getLandFlag(flagname);
					if(flag != null) continue;
					final Set<String> flagpars = entry.getValue();
					if(!flagpars.isEmpty()) flagpars.clear();
					it.remove();
					update = true;
				}
				if(update) land.updateFlags();
			}
		}
	}
}